package org.qhhc.thread.synchronizedStudy.SynTest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SynchronizedLock {
    private static final Object lock = new Object();
    private static int counter = 0;

    public static void main(String[] args) {
        // 单线程偏向锁验证
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                synchronized (lock) { counter++; } // 偏向锁生效
            }
        }).start();

        // 多线程轻量级锁验证
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                synchronized (lock) { counter++; } // 轻量级锁自旋
            }).start();
        }

        // 高并发重量级锁验证
        ExecutorService executor = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            executor.submit(() -> {
                synchronized (lock) { counter++; } // 升级为重量级锁
            });
        }
        executor.shutdown();
    }
}